/*
 * FreeModbus Libary: MSP430 Port
 * Copyright (C) 2006 Christian Walter <wolti@sil.at>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * File: $Id$
 */

/* ----------------------- Platform includes --------------------------------*/
#include "port.h"

/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h" 
/* ----------------------- Start implementation -----------------------------*/
BOOL
xMBPortTimersInit( USHORT usTim1Timeout50us )
{
    /* ----------------------------------------------------------------------------
    TIMER1 Configuration:
    F(CK_TIMER14) = 64MHz

    中断周期 = (PSC+1) * (TIMER14_ARR) / F(CK_TIMER14)

    函数目的：让TIMER14每 (usTim1Timeout50us*50us) 溢出一次，即中断一次
    ---------------------------------------------------------------------------- */
    //打开TIMER14时钟
    RCC->APBENR2 |= (1<<15);
    //配置PSC、ARR
    TIM14->PSC = 64-1;
    TIM14->ARR = 50 * usTim1Timeout50us;
    TIM14->CNT = 0;
    //清除溢出标志位
    TIM14 -> SR &=~ (1<<0);
    //使能溢出中断
    TIM14 -> DIER |= (1<<0);
    //先关闭CNT
    TIM14 -> CR1 &=~ (1<<0);
    //使能NVIC
    NVIC_EnableIRQ(TIM14_IRQn);
	return TRUE;
}


void
vMBPortTimersEnable( void )
{
    /* Reset timer counter and set compare interrupt. */
   //计数器归零
   TIM14->CNT = 0;
   //打开计数器
   TIM14 -> CR1 |= (1<<0);
   //使能溢出中断
   TIM14 -> DIER |= (1<<0);
}

void
vMBPortTimersDisable( void )
{
    //关闭CNT
    TIM14 -> CR1 &=~ (1<<0);
    //失能溢出中断
    TIM14 -> DIER &=~ (1<<0);
}

void TIM14_IRQHandler(void)
{
     if ( ( (TIM14->SR) & (1<<0) ) != 0) {
        TIM14 -> SR &=~ (1<<0);
        ( void )pxMBPortCBTimerExpired(  );
     }    
}
